package br.com.djiadreams.loginecadastro;

import br.com.djiadreams.georeferencedsignalproject.R;
import br.com.djiadreams.telas.TelaPrincipal;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Login extends Activity {
	private SharedPreferences preferencias;
	private ProgressDialog progresso;
	private LoginWebService loginWeb;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		preferencias = getSharedPreferences("login_preferencias", MODE_PRIVATE);
		try {
			boolean conectado = preferencias.getBoolean("conectado", false);
			if (conectado) {
				Intent telaPrincipal = new Intent(this, TelaPrincipal.class);
				startActivityForResult(telaPrincipal, 1);
			}
		} catch (Exception e) {
			Log.v("Login", "Primeiro Login, prefer�ncias vazias");
		}
		setContentView(R.layout.activity_login);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		// se voltou pra c� depois da telaPrincipal, eu mato a aplica��o...
		if (requestCode == 1) {
			finish();
		}
		super.onActivityResult(requestCode, resultCode, data);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	public void voltaFoco(EditText e, int ID) {
		// faz o teclado esconder de novo
		((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
				.hideSoftInputFromWindow(e.getWindowToken(), 0);
		LinearLayout l = (LinearLayout) findViewById(ID);
		l.requestFocus();

	}

	public void cadastrar(View v) {
		Intent cadastro = new Intent(this, Cadastro.class);
		startActivity(cadastro);
	}

	public void anonimo(View v) {
		Intent anonimo = new Intent(this, TelaPrincipal.class);
		startActivityForResult(anonimo, 1);
	}

	public void entrar(View v) {
		EditText n = (EditText) findViewById(R.id.nome);
		EditText s = (EditText) findViewById(R.id.senha);
		CheckBox m = (CheckBox) findViewById(R.id.manter_conectado);
		Editor editor = preferencias.edit();
		if (m.isChecked()) {
			editor.putBoolean("conectado", true);
		} else {
			editor.putBoolean("conectado", false);
		}
		editor.commit();

		try {
			String nome = n.getText().toString();
			String senha = s.getText().toString();
			if (nome.equals("") || senha.equals("")) {
				Toast.makeText(this, "Entrada inv�lida", Toast.LENGTH_SHORT)
						.show();
				voltaFoco(s,R.id.l_login);
				return;
			}
			DadosLogin infos = new DadosLogin(nome, senha);
			progresso = ProgressDialog.show(this, "Logando...",
					"Aguarde um instante");
			loginWeb = new LoginWebService();
			loginWeb.execute(infos);

		} catch (Exception e) {
			Toast.makeText(this, "Entradas inv�lidas", Toast.LENGTH_SHORT)
					.show();
			Log.v("EditText em branco", "Entrada inv�lida");
		} finally {
			n.setText(null);
			s.setText(null);
			voltaFoco(s,R.id.l_login);
		}

	}

	private class LoginWebService extends AsyncTask<DadosLogin, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progresso.show();
		}

		@Override
		protected Boolean doInBackground(DadosLogin... params) {
			return logando(params[0]);
		}

		private Boolean logando(DadosLogin dadosLogin) {
			// TODO Auto-generated method stub
			Thread timer = new Thread() {
				@Override
				public void run() {
					try {
						sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
			timer.start();
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			progresso.dismiss();
		}
	}
}
